import { Request, Response, NextFunction } from 'express';
import HttpStatusCodes from '@src/common/HttpStatusCodes';
import Joi from 'joi';
import { resExample } from '@src/services/common/responseData';

// 通用的验证中间件函数，传入一个验证规则
const validateGlobal = (
  schema: Joi.ObjectSchema,
  target: 'body' | 'query' | 'params' = 'body'
) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const { error } = schema.validate(req[target]);

    if (error) {
      next(resExample<null>({
        code: HttpStatusCodes.BAD_REQUEST,
        success: false,
        data: null,
        message: error.details.map((detail) => detail.message).join(', '),
      }));
    }

    next();
  };
};

export default validateGlobal;